package com.sefer.dragonfly.client.tools;

import java.text.MessageFormat;

import javax.management.MBeanOperationInfo;

import org.apache.log4j.Logger;

import com.sefer.dragonfly.client.core.container.MonitorContainer;
import com.sefer.dragonfly.client.core.domain.lifecycle.BaseLifecycle;
import com.sefer.dragonfly.client.core.domain.mbean.annotation.CMbean;
import com.sefer.dragonfly.client.core.domain.mbean.annotation.CMbeanMethod;
import com.sefer.dragonfly.client.core.exception.DragonFlyException;
import com.sefer.dragonfly.client.utils.MBeanAnnotationRegister;

/**
 * 监控客户端,启动所有插件及服务
 * 
 * @author xiaofeng 2011-9-9 上午09:36:35
 */
@CMbean
public class MonitorManage extends BaseLifecycle {

	private static final Logger logger = Logger.getLogger(MonitorManage.class);
	private volatile static MonitorManage monitorClient;

	private MonitorManage() {
	}

	public static MonitorManage getInstance() {
		synchronized (MonitorManage.class) {
			if (null == monitorClient) {
				monitorClient = new MonitorManage();
			}
		}

		return monitorClient;
	}

	public void init() {
		super.init();
		try {
			MonitorContainer.getContainer().init();
		} catch (DragonFlyException e) {
			logger.warn(MessageFormat.format(
					"MonitorContainer inite exception. ===> {0}",
					e.getMessage()), e);
		}
		logger.warn("MonitorClient inited");
	}

	@CMbeanMethod(description = "MonitorManage start", impact = MBeanOperationInfo.ACTION_INFO)
	public void start() {
		super.start();
		try {
			MonitorContainer.getContainer().start();
		} catch (DragonFlyException e) {
			logger.warn(MessageFormat.format(
					"MonitorContainer start exception. ===> {0}",
					e.getMessage()), e);
		}
		MBeanAnnotationRegister.register(this);
		logger.warn("MonitorClient started");
	}

	@CMbeanMethod(description = "MonitorManage stop", impact = MBeanOperationInfo.ACTION_INFO)
	public void stop() {
		super.stop();
		try {
			MonitorContainer.getContainer().stop();
		} catch (DragonFlyException e) {
			logger.warn(
					MessageFormat.format(
							"MonitorContainer stop exception. ===> {0}",
							e.getMessage()), e);
		}
		logger.warn("MonitorClient stoped");
	}

	/**
	 * Client mbean 不会销毁，需要通过该通道重新启动监控
	 */
	@CMbeanMethod(description = "MonitorManage destory", impact = MBeanOperationInfo.ACTION_INFO)
	public void destory() {
		super.destory();

		try {
			MonitorContainer.getContainer().destory();
		} catch (DragonFlyException e) {
			logger.warn(MessageFormat.format(
					"MonitorContainer destory exception. ===> {0}",
					e.getMessage()), e);
		}
		MBeanAnnotationRegister.unRegister(this);
		logger.warn("MonitorClient destoried");
	}

}
